package com.minelx.statementplus.ui.form.service.tablemapping;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.minelx.util.Files;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;
import java.util.Set;

import static java.util.stream.Collectors.toList;

public class TableMappingFactory {

	private final JSONObject mappings;

	private TableMappingFactory(JSONObject mappings) {
		this.mappings = mappings;
	}

	public TableMapping createMapping(String mappingKey) {
		if (!mappings.containsKey(mappingKey)) {
			throw new IllegalArgumentException("no mapping found: " + mappingKey);
		}
		return new TableMapping(mappings.getJSONObject(mappingKey));
	}

	public CompositeTableMapping createMapping(List<String> mappingKeys) {
		return new CompositeTableMapping(mappingKeys.stream().map(this::createMapping).collect(toList()));
	}

	public Set<String> mappingNames() {
		return mappings.keySet();
	}

	public static TableMappingFactory create(JSONObject mappings) {
		return new TableMappingFactory(mappings);
	}

	public static TableMappingFactory configuredMappings() {
		String content = Files.toString(Objects.requireNonNull(TableMappingFactory.class.getResourceAsStream("/tables_mapping.json")), StandardCharsets.UTF_8);
		return create(JSON.parseObject(content));
	}
}